import React, { PureComponent } from 'react'
import PropTypes from 'prop-types'
import CoreLayout from 'containers/layout'
import { connect } from 'react-redux'
import { getDataSource, getFlagValue, showTeam, getTeamFlag, getPageFlag, strengthLevel, STRENGTH_LEVEL } from 'services/utils'
import { Form, Input, Divider, Button, Icon, Progress } from 'antd'
import PubSub from 'pubsub-js'
import moment from 'moment'
import _ from 'lodash'
import 'styles/account.scss'
import EditPassword from './components/edit-password'
import EditEmail from './components/edit-email'
import QueueAnim from 'rc-queue-anim'

const FormItem = Form.Item
const accessFlag = getPageFlag('/account/secure', 'access')

@connect(
  state => ({
    auth                : state.Passport.auth,
    teams               : state.Passport.teams
  }),
)
@Form.create()
export default class Secure extends PureComponent {

  state = {
    StrengthLevel: {
      ...STRENGTH_LEVEL.VERY_WEAK,
      value: 0
    },
    editMode: null
  }

  componentDidMount () {
    setTimeout(() => {
      this.setState({ StrengthLevel: {
        ...strengthLevel(this.props.auth.strength),
        value: this.props.auth.strength
      }})
    }, 500)
    
  }
  
  render () {
    const { location, auth, teams, form } = this.props
    const { getFieldDecorator } = form
    const options = {
      location,
      pageCode: accessFlag.value,
      breadcrumb: [
        { name: '主页', link: '/' },
        { name: '个人中心' },
        { name: '安全设置' }
      ],
    }
    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 16 },
    }
    let editModeView = (
      <div style={{ maxWidth: 1200, margin: 'auto' }} key="default">
        <div className="account-avatar">
          <div className="avatar">
            <Icon type="user" />
          </div>
          <div className="summary">
            <p>登录账号：{auth.username}</p>
            <p>账号ID：{auth._id}</p>
            <p>注册时间：{moment(auth.createAt).format('YYYY-MM-DD HH:mm:ss')}</p>
            <p><a >修改头像</a></p>
          </div>
        </div>
        <Divider />
        <div className="secure-level">
          <div className="pull-left">账号安全程度</div>
          <Progress 
            percent={this.state.StrengthLevel['value']} 
            className={this.state.StrengthLevel['className']} 
            style={{ marginLeft: 30, width: 350 }} 
            showInfo={false} />
          <span style={{ marginLeft: 30 }}>安全级别：</span>
          <span className="secure-level-text" style={{ color: this.state.StrengthLevel['color'] }}>{this.state.StrengthLevel['name']}</span>
        </div>
        <Divider dashed />
        <SecuritySettingsItem
          name="登录密码"
          content="安全性高的密码可以使帐号更安全。建议您定期更换密码，设置一个包含字母，符号或数字且长度超过6位的密码。"
          onPressSetting={() => this.setState({ editMode: 'password' })}
          isSetting
        />
        <Divider dashed />
        <SecuritySettingsItem
          name="备用邮箱"
          content={(
            <span>
              您已绑定了邮箱<span className="success">{showEmail(auth.email)}</span> [我们发送的各类系统、服务通知将发送到您的备用邮箱。]
            </span>
          )}
          onPressSetting={() => this.setState({ editMode: 'email' })}
          isSetting
        />
      </div>
    )
    if (this.state.editMode === 'password') {
      editModeView = (
        <QueueAnim component="div" type={['right', 'left']}>
          <EditPassword
            onPressClose={() => this.setState({ editMode: null })}
            user={auth}
            key="password"
            />
        </QueueAnim>
      )
    }
    if (this.state.editMode === 'email') {
      editModeView = (
        <QueueAnim component="div" type={['right', 'left']}>
          <EditEmail
            onPressClose={() => this.setState({ editMode: null })}
            user={auth}
            key="email"
            />
        </QueueAnim>
      )
    }
    return (
      <CoreLayout {...options}>
        {editModeView}
      </CoreLayout>
    )
  }
}

class SecuritySettingsItem extends PureComponent {

  static propTypes = {
    name: PropTypes.string,
    content: PropTypes.oneOfType([PropTypes.string, PropTypes.element]),
    isSetting: PropTypes.bool,
    onPressSetting: PropTypes.func
  }

  static defaultProps = {
    name: undefined,
    content: undefined,
    isSetting: false,
    onPressSetting: () => null
  }

  render () {
    const { name, content, isSetting, onPressSetting } = this.props
    return (
      <div className="security-settings">
        <div>
          <div className="pull-left"><b>{name}</b></div>
          <div className="content">{content}</div>
        </div>
        <div className={`pull-right ${isSetting ? 'success' : 'warning'}`}>
          <Icon type={isSetting ? 'check-circle-o' : 'exclamation-circle-o'} />
          <span>{isSetting ? '已设置' : '未设置'}</span>
          <Divider type="vertical" />
          <a onClick={onPressSetting}>设置</a>
        </div>
      </div>
    )
  }

}

const showEmail = (email, start = 4) => {
  if (_.isEmpty(email)) {
    return ''
  }
  let name_str = email.replace(/([@][^@]+)$/, '')
  let suffix = email.match(/([@][^@]+)$/)
  let len = name_str.length - start
  let reg = new RegExp(`.(?!.*.{${len}})`, 'g')
  let new_name = name_str
  if (len > 1) {
    new_name = name_str.replace(reg, '*')
  }
  return `${new_name}${suffix[0]}`
}